<?php
/**
 * Контроллер ползователей
 * 
 * Управление тегами
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Класс контроллера для управления пользователями
 *
 */
class ControllerUser extends Element{
	/**
	 * Констуктор
	 *
	 * @param string $className имя контроллера
	 */
	public function __construct($className=null){
		$this->name='user';
		parent::__construct($className?$className:__CLASS__);
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function show($page=1){
		parent::show();
		import('model.user_to_user');
		import('model.user');
		$params=array(
		  'join'=>array(
		      'LEFT JOIN '.DB::apostrof(ModelUser_to_user::TABLE).' ON ('.
		      DB::apostrof(ModelUser_to_user::TABLE.DOT.ModelUser_to_user::F_USER_ID).'='.Core::user().
		      ' AND '.DB::apostrof(ModelUser_to_user::TABLE.DOT.ModelUser_to_user::F_RELATION_ID).'='.DB::apostrof(ModelUser::TABLE.DOT.ModelUser::F_USER_ID).') OR ('.
		      DB::apostrof(ModelUser_to_user::TABLE.DOT.ModelUser_to_user::F_USER_ID).'='.DB::apostrof(ModelUser::TABLE.DOT.ModelUser::F_USER_ID).
		      ' AND '.DB::apostrof(ModelUser_to_user::TABLE.DOT.ModelUser_to_user::F_RELATION_ID).'='.Core::user().')'
		  )
		);
		if($page){
		    $params['pagination']=array(
				'page'=>$page,
				'show'=>true
			);
		}
		$this->view->set(
			'list',
			$this->model()->load(
				false,
				array(
					ModelUser::TABLE.DOT.ModelUser::F_USER_ID,
					ModelUser::F_NAME,
					ModelUser_to_user::TABLE.DOT.ModelUser_to_user::F_MODE,
					ModelUser_to_user::TABLE.DOT.ModelUser_to_user::F_RELATION_ID
				),$params
			)
		);
		$this->view->set('pagination',$this->model()->pagination);
        $this->build();
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function display(){
		parent::display(true);
		$mode = Requestlocal::getString('mode',null);
		$info=$this->model()->loadOne($this->id);
		$info['birthday'] = date('d/m/Y', strtotime($info['birthday']));
		if($mode == 'edit'){
			$city = $this->model('region')->loadOne($info['city_id'],array(ModelRegion::F_TITLE, ModelRegion::F_PARENT_ID));
			if(isset($city['title'])){
				$info['city'] = $city['title'];
				$info['country'] = $this->model('region')->loadOne($info['country_id'],ModelRegion::F_TITLE);
			}
			
		}else{
			$info['articles'] = $this->model('article')->loadCount(array('where'=>ModelArticle::F_USER_ID .'='.$this->id));
			$info['shops'] = $this->model('shop')->load(false,array(ModelShop::F_NAME),array('where'=>ModelShop::F_USER_ID .'='.$this->id));
		}
		unset($info['password']); /// МОЖЕТ И НЕ НАДО
		$info['image'] = import('helper.image',true)->get($info['image_id']);
		$this->view->set('info',$info);
		$this->build($view);
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function getAddress(){
		parent::display(true);
		$mode = Requestlocal::getString('mode',null);
		$info=$this->model()->loadOne($this->id,array(ModelUser::F_CITY,ModelUser::F_CITY_ID,ModelUser::F_COUNTRY_ID,ModelUser::F_USER_ID,ModelUser::F_TEL,ModelUser::F_NAME,ModelUser::F_ADDRESS));
		$city = $this->model('region')->loadOne($info['city_id'],array(ModelRegion::F_TITLE, ModelRegion::F_PARENT_ID));
		if(isset($city['title'])){
			$info['city'] = $city['title'];
			$info['country'] = $this->model('region')->loadOne($info['country_id'],ModelRegion::F_TITLE);
		}			
		$this->view->set('info',$info);
		$this->build($view);
	}
	/**
	 * Форма редактирования
	 *
	 */
	public function edit(){
		parent::edit(true);
		Core::mustLogin();
		$this->view->set('element',$this->model()->loadOne($this->id));
		$this->build();
	}
	/**
	 * Форма создания
	 *
	 */
	public function add(){
		parent::add();
		$this->build();
	}
    /**
    * Регистрация
    *
    */
    public function register(){
        $errors = array();
        if(!$this->model()->checkEmail(Requestlocal::getString('email'))){
            $errors[ModelUser::F_EMAIL] = T::_('Email exist');
        }else{
            if(!Requestlocal::getString('name')){
                $local = Vars::_(Requestlocal::REQUESTLOCAL);
                $email = explode('@', Requestlocal::getString('email'));
                $local['name'] = $email[0];
                Vars::_(Requestlocal::REQUESTLOCAL,$local);
            }
        }
        
        if(count($errors)){
            $this->view->result($errors);
            return;
        }
        $this->save();
    }
	/**
	 * Создание
	 *
	 */
	public function save(){
		parent::save();
		$id=Requestlocal::getInt('user_id',null,'post');
		if ($id) Core::mustLogin();
		$image_id = Requestlocal::getInt(ModelUser::F_IMAGE_ID, 0);
		if($id && !$image_id) $image_id = '0';
		import('model.user');
		$result = false;
		$saveData=array(
			ModelUser::F_GROUP_ID  		=> 1,
        	ModelUser::F_LANG_ID  		=> 1,
        	ModelUser::F_COUNTRY_ID   	=> 1,
        	ModelUser::F_CITY_ID   		=> 2,
        	ModelUser::F_IMAGE_ID  		=> $image_id,
        	
        	ModelUser::F_EMAIL  		=> Requestlocal::getString('email'),
        	
        	
        	
        	ModelUser::F_CITY  	 		=> Requestlocal::getString('city'),
        	ModelUser::F_ADDRESS		=> Requestlocal::getString('address'),
        	ModelUser::F_SEX			=> Requestlocal::getInt('sex'),
        	ModelUser::F_BIRTHDAY		=> Requestlocal::getString('birthday'),
        	ModelUser::F_SITE 			=> Requestlocal::getString('site'),
        	ModelUser::F_TEL			=> Requestlocal::getString('tel'),
        	ModelUser::F_ICQ			=> Requestlocal::getInt('icq'),
        	ModelUser::F_NAME			=> Requestlocal::getString('name'),
        	ModelUser::F_ABOUT			=> Requestlocal::getString('about')
		);
		
		if(!$id){
		    $saveData[ModelUser::F_REGISTRATION_DATE]=Core::date();
		    $saveData[ModelUser::F_REPUTATION]=0;
		    $saveData[ModelUser::F_BANNED]=0;
        	$saveData[ModelUser::F_MONEY]=0;
		    $saveData[ModelUser::F_CHECKED_EMAIL]=1;///поменять и сделать проверку
		}
		if($pass=Requestlocal::getString('password',null)){
		    $saveData[ModelUser::F_PASSWORD]=$pass;
		}elseif($id){
			unset($saveData[ModelUser::F_PASSWORD]);
		}else{
			$result = array(
				'user.password' => 'Поле должно быть заполненным',
				'user.test'=>'w'
			);
		}
		if (!$result) {
			$result=$this->model()->save($saveData,$id);
		}
		if(!$id && is_numeric($result)){
            $id = $result;
        }
        if(is_array($result)){
        	$this->view->result($result);
        } else {
        	if($image_id && $image_id!='0' && Requestlocal::getInt('newImage',0)){
            	import('helper.image',true)->setModule($image_id,'user',$id);
            } elseif (Requestlocal::getInt('newImage',0)){
            	import('helper.image',true)->deleteImageFromModule('user',$id);
            }
        	$this->view->result(false);
        }
	}
	/**
	 * Удаление
	 *
	 */
	public function delete(){
		parent::delete(true);
		Core::mustLogin();
		$this->model()->delete(Requestlocal::getInt('user_id'));
		Core::redirect(base64_decode(Vars::_(Core::REFERER)),T::_('Deleted'));
	}
}